package hhm.spring.security;

import com.alibaba.fastjson.JSON;
import hhm.spring.pojo.HHMResponse;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccHandler extends SimpleUrlAuthenticationSuccessHandler {

	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

	private SqlSession sqlSessionMySql;
	private SqlSessionFactory sqlSessionFactoryMySql;

	@Override
	protected void handle(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException {

		if (response.isCommitted()) {
			System.out.println("Can't redirect");
			return;
		}
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");

		HHMResponse hhmResponse = new HHMResponse();
		hhmResponse.setSuccess(true).setMsg("登陆成功");
		response.getWriter().println(JSON.toJSON(hhmResponse));
		response.getWriter().flush();

	}




	@Override
	public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
		this.redirectStrategy = redirectStrategy;
	}

	@Override
	protected RedirectStrategy getRedirectStrategy() {
		return redirectStrategy;
	}

	public SqlSession getSqlSessionMySql() {
		return sqlSessionMySql;
	}

	public void setSqlSessionMySql(SqlSession sqlSessionMySql) {
		this.sqlSessionMySql = sqlSessionMySql;
	}

	public SqlSessionFactory getSqlSessionFactoryMySql() {
		return sqlSessionFactoryMySql;
	}

	public void setSqlSessionFactoryMySql(
			SqlSessionFactory sqlSessionFactoryMySql) {
		this.sqlSessionFactoryMySql = sqlSessionFactoryMySql;
	}

}